﻿using System;
using System.Linq;
using Csla;
using Csla.Data;
using Csla.Serialization;
using BizControl.DalLinq;
using BizControl.Library.Security;
using System.Security;
using BizControl.Resources;
using BizControl.Library.BusinessObjects.Models;

namespace BizControl.Library.BusinessObjects.Marks
{
  [Serializable()]
  public class PersonMarkList : ReadOnlyListBase<PersonMarkList, MarkInfo>
  {
    #region  Factory Methods

    public static PersonMarkList GetPersonMarkList()
    {
      return DataPortal.Fetch<PersonMarkList>();
    }

    public static PersonMarkList GetPersonMarkList(string name)
    {
      return DataPortal.Fetch<PersonMarkList>(new SingleCriteria<PersonMarkList, string>(name));
    }

    private PersonMarkList()
    { /* require use of factory methods */ }

    #endregion

    #region  Data Access

    private void DataPortal_Fetch()
    {
      // fetch with no filter
      Fetch("");
    }

    private void DataPortal_Fetch(SingleCriteria<PersonMarkList, string> criteria)
    {
      Fetch(criteria.Value);
    }

    private void Fetch(string nameFilter)
    {
      RaiseListChangedEvents = false;
      var currentModel = SecurityChecks.GetCurrentModel();
      using (var ctx = ContextManager<BusinessControl2DataContext>.GetManager(Database.BizControlDB))
      {
        var data = from m in ctx.DataContext.Marks
                   where !m.IsDeleted && m.Model == currentModel.ModelId && m.Tag == PersonMarkBO.PersonMarkTagName
                   select new MarkInfo(m.MarkId, m.Name, m.Tag, m.IsActive);
        if (!(string.IsNullOrEmpty(nameFilter)))
        {
          data = from m in ctx.DataContext.Marks
                 where m.Name.Contains(nameFilter) && !m.IsDeleted && m.Model == currentModel.ModelId && m.Tag == PersonMarkBO.PersonMarkTagName
                 select new MarkInfo(m.MarkId, m.Name, m.Tag, m.IsActive);
        }
        IsReadOnly = false;
        this.AddRange(data);
        IsReadOnly = true;
      }
      RaiseListChangedEvents = true;
    }

    #endregion

  }
}
